package com.yamawa.app;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by thl on 2016-03-24.
 */
public class WebViewActivity extends AppCompatActivity {
    @Bind(R.id.act_web_webView)
    WebView webView;
    @Bind(R.id.act_web_pro)
    ProgressBar progressBar;
    @Bind(R.id.loadlayout)
    LoadLayout loadLayout;
    private Intent intent;
    private WebSettings webSetting;
    private String url = "";
    private String webContent;
    private boolean fullScreen = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.act_web_view);
        ButterKnife.bind(this);

        initObject(savedInstanceState);
        initData(savedInstanceState);
        initListener();
    }

    public void initObject(@NonNull Bundle savedInstanceState) {
    }

    public void initData(@NonNull Bundle savedInstanceState) {
        intent = getIntent();
        if (intent != null) {
            url = intent.getStringExtra("url");
            webContent = intent.getStringExtra("webContent");
            fullScreen = intent.getBooleanExtra("fullScreen", fullScreen);
        }

        if (fullScreen) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

        webSetting = webView.getSettings();
        //支持javascript
        webSetting.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webSetting.setSupportZoom(true);
        // 设置出现缩放工具
        webSetting.setBuiltInZoomControls(false);
        //扩大比例的缩放
        webSetting.setUseWideViewPort(true);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setLoadWithOverviewMode(true);

        if (!TxtUtil.isEmpty(url)) {
            webView.loadUrl(url);
        } else {
            webView.loadDataWithBaseURL(null, webContent, "text/html", "UTF-8", null);
        }
        loadLayout.setStatus(LoadLayout.TYPE_LOADING);
    }

    public void initListener() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    loadLayout.setStatus(LoadLayout.TYPE_SUCCESS);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                    loadLayout.setStatus(LoadLayout.TYPE_LOADING);
                }
            }


        });

        //如果不设置WebViewClient，请求会跳转系统浏览器
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242

                if (!TxtUtil.isEmpty(url)) {
                    view.loadUrl(url);
                    return true;
                }

                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (!TxtUtil.isEmpty(request.getUrl().toString())) {
                        view.loadUrl(request.getUrl().toString());
                        return true;
                    }
                }

                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                view.stopLoading();
                Message msg = handler.obtainMessage();//发送通知，加入线程
                msg.what = -1;//通知加载自定义404页面
                handler.sendMessage(msg);//通知发送！
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.stopLoading();
                Message msg = handler.obtainMessage();//发送通知，加入线程
                msg.what = -1;//通知加载自定义404页面
                handler.sendMessage(msg);//通知发送！
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            }
        });

        loadLayout.setReloadListener(new LoadLayout.OnReloadListener() {
            @Override
            public void onReload() {
                webView.reload();
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    progressBar.setVisibility(View.GONE);
                    loadLayout.setStatus(LoadLayout.TYPE_ERROR);
                    break;
            }
        }
    };

    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class TopBarClickedListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
//                case R.id.top_bar_back:
//                    if (webView.canGoBack()) {
//                        webView.goBack(); // goBack()表示返回WebView的上一页面
//                    } else {
//                        finish();
//                    }
//                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        hideKeyboard();
        super.onPause();
    }

    private void hideKeyboard() {
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }
}
